#include <iostream>
#include <functional>
#include <memory>
#include <thread>
#include <future>
#include <mutex>
#include <condition_variable>
#include <vector>

class ThreadPool
{
    using Functor = std::function<void(void)>;

public:
    ThreadPool(int thread_count = 1)
        : _stop(false)
    {
        for (int i = 0; i < thread_count; ++i)
        {
            _threadpool.emplace_back(&ThreadPool::entry, this);
        }
    }

    ~ThreadPool()
    {
        stop();
    }

    void stop()
    {
        // if (_stop == true)
        //     return;
        _stop = true;
        _cv.notify_all();
        for (auto &thread : _threadpool) // &thread
        {
            thread.join();
        }
    }

    template <typename F, typename... Args>
    auto push(F &&func, Args &&...args) -> std::future<decltype(func(args...))>
    {
        // 传入的函数封装为一个可调用对象
        using return_type = decltype(func(args...));
        auto tmp_func = std::bind(std::forward<F>(func), std::forward<Args>(args)...);
        auto task = std::make_shared<std::packaged_task<return_type()>>(tmp_func);
        std::future<return_type> fut = task->get_future();
        // 构建一个lambda表达式，捕获任务对象
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _taskpool.push_back([task]()
                                { (*task)(); });
            _cv.notify_one();
            // 将匿名对象抛入到任务池中
        }
        return fut;
    }

private:
    // 线程入口函数
    void entry()
    {
        while (!_stop)
        {
            std::vector<Functor> tmp_taskpool;
            {
                // mutex
                std::unique_lock<std::mutex> lock(_mutex);

                // 任务池不为空 或 _stop
                _cv.wait(lock, [this]()
                         { return _stop || !_taskpool.empty(); });

                if (_stop && _taskpool.empty())
                    return;

                tmp_taskpool.swap(_taskpool);
            }
            for (auto &task : tmp_taskpool)
            {
                task();
            }
        }
    }

private:
    std::atomic<bool> _stop;
    std::vector<Functor> _taskpool;       // task pool
    std::vector<std::thread> _threadpool; // thread pool
    std::condition_variable _cv;
    std::mutex _mutex;
};

int Add(int a, int b)
{
    return a + b;
}

int main()
{
    ThreadPool threadpool;
    for (int i = 0; i < 10; ++i)
    {
        std::future<int> fu = threadpool.push(Add, i + 1, i + 2);
        std::cout << fu.get() << std::endl;
    }

    return 0;
}